Skip to main content

Limit DOM Updates

A common mistake seen in JavaScript when run in a browser environment is updating the DOM more often than necessary.

The issue here is that every update in the DOM interface causes the browser to re-render the screen. If an update changes the layout of an element in the page, the entire page layout needs to be re-computed, and this is very performance-heavy even in the simplest of cases. The process of re-drawing a page is known as reflow and can cause a browser to run slowly or even become unresponsive. The consequence of updating the document too frequently is illustrated with the following example of adding items to a list. Consider the following document containing a <ul> element:

<!DOCTYPE html> <html>
<body>
<ul id="list"></ul>
</body>
</html>

We add 5000 items to the list looping 5000 times (you can try this with a larger number on a powerful computer to increase the effect).

var list = document.getElementById("list"); for(var i = 1; i <= 5000; i++) {
list.innerHTML += `<li>item ${i}</li>`; // update 5000 times }

In this case, the performance can be improved by batching all 5000 changes in one single DOM update.

var list = document.getElementById("list"); var html = "";
for(var i = 1; i <= 5000; i++) {
html += `<li>item ${i}</li>`;
}
list.innerHTML = html; // update once

The function document.createDocumentFragment() can be used as a lightweight container for the HTML created by the loop. This method is slightly faster than modifying the container element's innerHTML property (as shown below).

var list = document.getElementById("list");
var fragment = document.createDocumentFragment(); for(var i = 1; i <= 5000; i++) {
li = document.createElement("li");
li.innerHTML = "item " + i;
fragment.appendChild(li);
i++;
}
list.appendChild(fragment);